package com.ntlg.securityspringboot.securityConfig;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /*进行授权操作*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                /*（/）表示主页请求，(permitAll())表全部拥有此授权*/
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("v1")
                .antMatchers("/level2/**").hasRole("v2")
                .antMatchers("/level3/**").hasRole("v3");



                /*当没有权限时跳转到此登陆页(系统自带)*/
               /*http.formLogin();*/
               /*进入自带的登陆页*/
              http.formLogin().loginPage("/toLogin")
                      .usernameParameter("username")
                      .passwordParameter("password")
                      .loginProcessingUrl("/login");

               /*登陆注销操作
               * 1.在前面添加一个按钮链接th:href=@{/logout}
               * 注销后跳转到(/)链接页面
               * 2.http.logout().logoutSuccessUrl("/")
               * */
               http.csrf().disable();
               http.logout().logoutSuccessUrl("/");

               /*使用自带的登陆页面所以remember me 要改变*/
       /* http.rememberMe();*/
        http.rememberMe().rememberMeParameter("remeberme");
    }

    /*进行认证操作*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("root")).roles("v1","v2","v3")
                .and()
                .withUser("ryc").password(new BCryptPasswordEncoder().encode("1998")).roles("v1")
                .and()
                .withUser("jj").password(new BCryptPasswordEncoder().encode("cc")).roles("v2","v3");
    }
}
